﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class main_MovieSelection : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            // 绑定日期数据（今天、明天、后天、大后天）
            DataTable dtDates = new DataTable();
            dtDates.Columns.Add("DateValue");
            dtDates.Columns.Add("DisplayText");

            for (int i = 0; i < 4; i++)
            {
                DateTime date = DateTime.Now.AddDays(i);
                dtDates.Rows.Add(
                    date.ToString("yyyy-MM-dd"),
                    GetRelativeDateDisplayText(date, i)
                );
            }

            rptDates.DataSource = dtDates;
            rptDates.DataBind();
        }
    }

    private string GetRelativeDateDisplayText(DateTime date, int dayOffset)
    {
        string dayText = "";
        switch (dayOffset)
        {
            case 0: dayText = "今天"; break;
            case 1: dayText = "明天"; break;
            case 2: dayText = "后天"; break;
            default: dayText = date.ToString("dddd", new System.Globalization.CultureInfo("zh-CN")); break;
        }
        return $"{dayText}({date.Month}月{date.Day}日)";
    }

    protected void btnBook_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "Book")
        {
            string[] args = e.CommandArgument.ToString().Split('|');
            string hallId = args[0];
            string hallNumber = args[1];
            string startTime = args[2];
            string endTime = args[3];

            // 跳转到选座页面
            Response.Redirect($"SeatSelection.aspx?hallId={hallId}&hallNumber={hallNumber}&startTime={startTime}&endTime={endTime}");
        }
    }
    protected void gvSchedules_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Book")
        {
            string[] args = e.CommandArgument.ToString().Split('|');
            string hallId = args[0];
            string hallNumber = args[1];
            string startTime = args[2];
            string endTime = args[3];
            string selectedDate = GetSelectedDate();

            // 跳转到对应放映厅的选座页面，传递所有必要参数
            Response.Redirect($"SeatSelection.aspx?hallId={hallId}&hallNumber={hallNumber}&date={selectedDate}&startTime={startTime}&endTime={endTime}");
        }
    }
    protected string FormatTimeRange(object startTime, object endTime)
    {
        try
        {
            // 处理SQL Time类型（实际可能是TimeSpan）
            TimeSpan start = (TimeSpan)startTime;
            TimeSpan end = (TimeSpan)endTime;
            return $"{start:hh\\:mm} - {end:hh\\:mm}";
        }
        catch
        {
            return "时间数据异常";
        }
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        string eventArgument = Request.Form["__EVENTARGUMENT"];
        if (!string.IsNullOrEmpty(eventArgument))
        {
            if (eventArgument.StartsWith("SelectMovie:"))
            {
                string movieId = eventArgument.Split(':')[1];
                LoadMovieDetails(movieId);

                // 获取电影名称
                string movieName = GetMovieNameById(movieId);
                sqlDataSourceSchedules.SelectParameters["MovieName"].DefaultValue = movieName;
                sqlDataSourceSchedules.SelectParameters["ShowDate"].DefaultValue = GetSelectedDate();
                gvSchedules.DataBind();
            }
            else if (eventArgument.StartsWith("SelectDate:"))
            {
                string date = eventArgument.Split(':')[1];
                sqlDataSourceSchedules.SelectParameters["ShowDate"].DefaultValue = date;
                gvSchedules.DataBind();
            }
        }
    }
    private string GetMovieNameById(string movieId)
    {
        string movieName = "";
        string connectionString = ConfigurationManager.ConnectionStrings["MovieDBConnectionString"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "SELECT Title FROM Movies WHERE MovieID = @MovieID";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@MovieID", movieId);

            connection.Open();
            movieName = command.ExecuteScalar()?.ToString();
            connection.Close();
        }
        return movieName;
    }

    private void LoadMovieDetails(string movieId)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "SELECT Title, PosterUrl, Rating, Duration, Genre, Actors FROM Movies WHERE MovieID = @MovieID";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@MovieID", movieId);

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                // 确保这些控件在页面上存在且runat="server"
                movieInfoContainer.Style["display"] = "block";
                movieTitle.InnerText = reader["Title"].ToString();

                movieRating.InnerText = reader["Rating"].ToString();
                movieDuration.InnerText = reader["Duration"].ToString();
                movieGenre.InnerText = reader["Genre"].ToString();
                movieActors.InnerText = reader["Actors"].ToString();
            }
            else
            {
                movieInfoContainer.Style["display"] = "none";
            }
            reader.Close();
        }
    }

    private string GetSelectedDate()
    {
        foreach (RepeaterItem item in rptDates.Items)
        {
            if (item.FindControl("dateItem") is HtmlGenericControl dateItem &&
                dateItem.Attributes["class"].Contains("active"))
            {
                return dateItem.Attributes["data-value"];
            }
        }
        return DateTime.Now.ToString("yyyy-MM-dd");
    }
}